package com.stn.zjx.givingtreasure.activity.location;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.came.viewbguilib.ButtonBgUi;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.adapter.AddressManagerItemListAdapter;
import com.stn.zjx.givingtreasure.adapter.LocationItemListAdapter;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.service.AmapLocationService;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserLocationActivity extends BaseActivity implements AMapLocationListener, PoiSearch.OnPoiSearchListener, Inputtips.InputtipsListener {
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_location_edit)
    EditText searchEdit;
    @BindView(R.id.rv)
    RecyclerView rv;
    AmapLocationService amapLocationService = null;
    @BindView(R.id.twinkling_refresh)
    TwinklingRefreshLayout twinklingRefresh;
    private String province = "";
    private String city = "";
    private String area = "";
    private String like = "";
    private String address="";
    public int currentPage = 1;
    private PoiSearch poiSearch;
    private boolean isMoreLoading = false;
    private int visibleItemCount = 0;
    private LinearLayoutManager lm;
    private LocationItemListAdapter adapter;
    private Integer pageSize=20;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.location));
        rv.setLayoutManager(lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false));
        rv.setAdapter(adapter = new LocationItemListAdapter(this));
        ProgressLayout headerView = new ProgressLayout(this);
        headerView.setColorSchemeResources(R.color.bg_red_orange, R.color.bg_red_orange1);
        twinklingRefresh.setHeaderView(headerView);
        twinklingRefresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                startLocation();
            }

            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {

            }
        });

        rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (isMoreLoading == false && newState == RecyclerView.SCROLL_STATE_IDLE && visibleItemCount == adapter.dataBeanList.size() - 1 &&
                        adapter.dataBeanList.size() >= currentPage * pageSize) {
                    initAppend(like);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                visibleItemCount = lm.findLastVisibleItemPosition();
            }
        });


        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(searchEdit.getText().toString().length()==0){

                    if(address.length()>(province.length()+city.length()+area.length())){
                        like=address.substring(province.length()+city.length()+area.length(),like.length());
                    }else{
                        like=address;
                    }
                    System.out.println("************like"+like);
                    initRefresh(like);
                }else{
                    like=searchEdit.getText().toString();
                    System.out.println("************like"+like);
                    initRefresh(like);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
       twinklingRefresh.startRefresh();

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_location);
        ButterKnife.bind(this);
        initComponent();


    }

    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;

        }
    }

    public void startLocation() {
        amapLocationService = new AmapLocationService(this);
        amapLocationService.registerListener(this);
        amapLocationService.start();

    }
    public void initRefresh(String querylike){
        currentPage=1;
        PoiSearch.Query query = new PoiSearch.Query(querylike, "", city);
        query.setPageSize(pageSize);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);//设置查询页码
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }
    public void initAppend(String querylike){
        currentPage++;
        PoiSearch.Query query = new PoiSearch.Query(querylike, "", city);
        query.setPageSize(pageSize);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);//设置查询页码
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        twinklingRefresh.finishRefreshing();

        if (aMapLocation.getErrorCode() == 0) {
            province=aMapLocation.getProvince();
            city = aMapLocation.getCity();
            area = aMapLocation.getDistrict();
            like=aMapLocation.getAddress();
            address=aMapLocation.getAddress();
            adapter.province=province;
            adapter.city=city;
            adapter.area=area;
            if(like.length()>(province.length()+city.length()+area.length())){
                like=like.substring(province.length()+city.length()+area.length(),like.length());
            }

            initRefresh(like);
        } else {
            showToast(aMapLocation.getErrorInfo());
        }
      //  dissmissLoading();
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        twinklingRefresh.finishRefreshing();

                if(currentPage==1){
                    adapter.refreshList(poiResult.getPois());
                }else{
                    adapter.appendList(poiResult.getPois());
                }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onGetInputtips(List<Tip> list, int i) {

    }
}
